//  获取数据
var $list = $(".cmts .list")
var $btn = $(".reply .btn")
var $user = $(".reply .user")
var $editor = $(".reply .editor")

// 获取后台数据
$.ajax({
    url: "http://localhost:3000/db",
    type: "GET",
    success: function (data) {
        // console.log(data)
        $list.html(template("tem", data));
        deleteData()
    }
})

// 添加点击事件 向数据库中添加新的数据
$btn.click(function () {
    var username = $user.val();
    var content = $editor.val();
    $.ajax({
        url: "http://localhost:3000/comments",
        type: "POST",
        dataType: "json",
        data: { username: username, content: content },
        success: function (data) {
            // console.log(data)
            $list.append(template("tem", { "comments": [data] }))
            deleteData()
        }
    })
    $user.val("");
    $editor.val("");
})

// 点击删除 删除留言
function deleteData() {
    $(".cmts .list .delete").click(function () {
        $li = $(this).parents("li");
        var index = $li.attr("uid");
        $.ajax({
            url: "http://localhost:3000/comments/" + index,
            type: "DELETE"
        })
        $li.remove();
    })
}